package com.example.smarthome;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private Button btnTime=null;
	private Button red = null;
	private Button blue = null;
	private Button green = null;
	private Button yellow = null;
	private Button pink = null;
	private Button cyan = null;
	private Button white = null;

	
	private TextView time=null;
	
	private int i=0;
	
	private boolean isTime= false;
	private Thread tThread=null;

	
	
	private Thread socketThread = null;
	private boolean isConnecting = false;
	private Button connect = null;
	
	private Socket socketClient = null;
	static BufferedReader  clientBufferedReader = null;
	static PrintWriter printWriter = null;
	
	private TextView result = null;
	
	
	
	private String ip="112.74.56.61";
	private int port = 8080;
	private String dvc_id = "id:002";
	
	private String ss=null;
	private Context mContext=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext=this;
		
		
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()        
        .detectDiskReads()        
        .detectDiskWrites()        
        .detectNetwork()   // or .detectAll() for all detectable problems       
        .penaltyLog()        
        .build());        
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()        
        .detectLeakedSqlLiteObjects()     
        .penaltyLog()        
        .penaltyDeath()        
        .build()); 
		

        /*
        *	按下红色按钮时后台响应的代码
		*/
		
		red=(Button)findViewById(R.id.red);		
		red.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{				    	
			    	printWriter.print("to:001:1");//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}			
			}});

		/*
        *	按下蓝色按钮时后台响应的代码
		*/
		blue=(Button)findViewById(R.id.blue);
		blue.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{				    	
			    	printWriter.print("to:001:3");//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}					
			}});

		/*
        *	按下绿色按钮时后台响应的代码
		*/
		green=(Button)findViewById(R.id.green);
		green.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{				    	
			    	printWriter.print("to:001:2");//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}					
			}});

		/*
        *	按下黄色按钮时后台响应的代码
		*/
		yellow=(Button)findViewById(R.id.yellow);
		yellow.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{				    	
			    	printWriter.print("to:001:4");//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}					
			}});

		/*
        *	按下粉色按钮时后台响应的代码
		*/
		pink=(Button)findViewById(R.id.pink);
		pink.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{				    	
			    	printWriter.print("to:001:5");//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}					
			}});			

		/*
        *	按下青色按钮时后台响应的代码
		*/
		cyan=(Button)findViewById(R.id.cyan);
		cyan.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{				    	
			    	printWriter.print("to:001:6");//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}					
			}});			

		/*
        *	按下白色按钮时后台响应的代码
		*/
		white=(Button)findViewById(R.id.white);
		white.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{				    	
			    	printWriter.print("to:001:0");//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}					
			}});			

		//btnTime是启动计数器的按钮
		btnTime=(Button)findViewById(R.id.button1);

		//time是显示数字的text view
		time =(TextView)findViewById(R.id.time);

		//接受数据的text view
		result = (TextView)findViewById(R.id.result);
		

		/*
		*
        *	按下定时器按钮时后台响应的代码
        *
		*/
		btnTime.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//判断isTime是否为true，即计数器是在计时
				if(isTime)
				{
					//把isTime设为false，用于下次按下计时器按钮后的判断
					isTime=false;
					//进程中断，即计数器停止计时
					tThread.interrupt();
					//调用回调函数，使计数器重0开始
					tHandler.removeCallbacks(tThread);
					i=0;
					time.setText(""+i);					
				}
				else
				{
					//如果isTime为false，则启动线程timeRunnable，开始计时，
					//并将isTime设为true，用于下次按下计时器按钮后的判断
					tThread= new Thread(timeRunnable);					
					tThread.start();
					isTime=true;
				}								
			}});

		/*
		*
        *	按下连接socket按钮时后台响应的代码
        *
		*/
		connect = (Button)findViewById(R.id.cnct);
		connect.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub			
				if(isConnecting)
				{
					//socket进程中断，类似上面定时器
					socketThread.interrupt();				
					isConnecting=false;
					//设置按钮上的文字
					connect.setText("连接已经关闭");
					//新增代码
					try {
						if(socketClient!=null)
						{
							socketClient.close();
							socketClient = null;
							
							printWriter.close();
							printWriter = null;
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
				}
				else
				{
					socketThread = new Thread(socketRunnable);
					socketThread.start();
					isConnecting = true;
					//设置按钮上的文字
					connect.setText("连接已经打开");
				}
				
				
			}});
		
	}

	//按钮连接socket的线程创建
	private Runnable socketRunnable = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			
			try {			
				//程序进入阻塞的状态
				//建立一个socket连接，服务器ip port
				socketClient = new Socket(ip,port);

				//定义一个流来接收信息
				//socketClient.getInputStream()创建输入流对象
				//new InputStreamReader(socketClient.getInputStream())创建输入流读取器对象 并传入输入流对象
				// （整句）该对象作用：获取服务器返回的数据
				clientBufferedReader = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
				//printWriter = new PrintWriter(socketClient.getOutputStream(), isConnecting);

				//从Socket 获得输出流对象OutputStream，该对象作用：发送数据
				printWriter = new PrintWriter(socketClient.getOutputStream(), true);

					
				Message msg=new Message();
				
				msg.what=2;

				socketHandler.sendMessage(msg);			
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//在命令行打印异常信息--程序中出错的位置及原因
				e.printStackTrace();
				
				//新加
				return;
			}
			
			char [] buffer = new char[256];
			int count;

			while(isConnecting)
			{

				try {
					if((count = clientBufferedReader.read(buffer))>0)
					{

						char [] bb = new char[count];
						
						for(int i=0;i<count;i++)
						{
							bb[i]=buffer[i];
						}
						//连接成功后，从服务器收到的数据保存在ss变量里面
						ss= new String(bb);

						//子线程中无法对 UI进行操作了。我们希望可以将服务器返回的内容显示 到界面上，
						// 所以就创建了一个 Message对象，并使用 Handler将它发送出去。
						// 之后又在 Handler 的 handleMessage()方法中对这条 Message进行处理，最终取出结果并设置到 TextView上
						Message msg = new Message();
						msg.what=1;
						socketHandler.sendMessage(msg);
						
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
		//	clientBufferedReader();
			
		}};
	
		//新加前序
		@SuppressLint("HandlerLeak")
		// 实例化主线程,用于更新接收过来的消息
		Handler socketHandler = new Handler(){
			
			public void handleMessage(Message msg){
				
				if(msg.what==2)
				{
					//msg.what==2时，准备连接服务器状态
					//点击按钮连接socket后，若连接成功，则显示这个数据
					result.setText("链接成功");

					try 
					{
						//发送id:002给服务器
				    	printWriter.print(dvc_id);
						//刷新printWrite的缓冲区
				    	printWriter.flush();
					}
					catch (Exception e) 
					{
						// TODO: handle exception
						//在手机页面显示发送异常
						Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
					}	
					
					

				}
				else if(msg.what==1)
				{
					//msg.what==1时，是已经连好服务器的状态
					//显示的数据是服务器发来的
					result.setText(ss);
				}
				
			};
			
		};
	
	

	//按钮定时器的线程创建
	private Runnable timeRunnable = new Runnable(){
		
		public void run(){
			if(isTime)
			{
				//定时器1s刷新一次
				tHandler.postDelayed(this, 1000);
				
				Message msg = new Message();
				
				msg.what=1;
				tHandler.sendMessage(msg);
				
			}
			else
				tHandler.removeCallbacks(tThread);
		}
		
	};
	
	 Handler tHandler = new Handler(){
		
		public void handleMessage(Message msg){
			
			if(msg.what==1)
			{
				i++;				
				time.setText(""+i);		

				//随机获取0-6数字
				int temp = (int)(Math.random()*10)%7;
				
				try 
				{				    	
			    	printWriter.print("to:001:" + temp);//发送给服务器
			    	printWriter.flush();
				}
				catch (Exception e) 
				{
					// TODO: handle exception
					Toast.makeText(mContext, "发送异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
				}			

				//每秒更换一次计数器的背景颜色
				switch(temp)
				{
					//红
				case 1:time.setBackgroundColor(0xffff0000);
					break;
					//绿
				case 2:time.setBackgroundColor(0xff00ff00);
					break;
					//蓝
				case 3:time.setBackgroundColor(0xff0000ff);
					break;
					//黄
				case 4:time.setBackgroundColor(0xffffff00);
					break;
					//粉
				case 5:time.setBackgroundColor(0xffff00ff);
						break;
					//青
				case 6:time.setBackgroundColor(0xff00ffff);
					break;
					//白
				case 0:time.setBackgroundColor(0xffffffff);
					break;					
				default:	time.setBackgroundColor(Color.RED);
					break;
				}
				
				
				
			}
			
		};
		
	};
	
	//新加声明周期
	public void onDestroy() {
		super.onDestroy();
		if (isConnecting) 
		{				
			isConnecting = false;
			try {
				if(socketClient!=null)
				{
					socketClient.close();
					socketClient = null;
					
					printWriter.close();
					printWriter = null;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			socketThread.interrupt();
		}
	}   
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
